//
//  XSOAthViewcontroller.swift
//  WeiDo
//
//  Created by XISHAN on 16/3/5.
//  Copyright © 2016年 XISHAN. All rights reserved.
//

import UIKit
import SVProgressHUD

let XSChangeRootVCNotification = "XSChangeRootVCNotification"


let OA_APPKEY = "2534384027"
let OA_APP_SECRET = "619171316bc926825b004fac19a7444f"
let OA_redirect_uri = "http://www.baidu.com/"

class XSOAthViewcontroller: UIViewController {

    
    lazy var OAthLoginUrl = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(OA_APPKEY)&redirect_uri=\(OA_redirect_uri)")!

    

    override func loadView() {
        
        self.view = webView
    
        let request = NSURLRequest(URL: OAthLoginUrl)
        
        webView.loadRequest(request)
        
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setupUI()
    
    }
    
    //设置导航栏
    private func setupUI(){
        
        navigationItem.rightBarButtonItem = UIBarButtonItem( title: "自动填充", target: self, action: "autoFill")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "back")
        navigationItem.title = "WeiBo"
        
    }
    
    //自动填充
    @objc private func autoFill(){
        
        let javaScriptStr = "document.getElementById('userId').value='zhangxishan@foxmail.com';document.getElementById('passwd').value='66551338'"
        
        webView.stringByEvaluatingJavaScriptFromString(javaScriptStr)
    }
    
    @objc private func back(){
        
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    private lazy var webView:UIWebView = {
    
        let webView = UIWebView()
        
        webView.delegate = self
        
        return webView
    }()
    
}

extension XSOAthViewcontroller:UIWebViewDelegate{
    
    //当webView加载某个请求时,会调用这个方法,询问是否加载请求,true就加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
        guard let url = request.URL else{
            return true
        }
        let urlString = url.absoluteString
        
        if urlString.hasPrefix(OA_redirect_uri){
            
            //query是url问好后面的那一串字符
            let query = url.query!
            
            let code = query.substringFromIndex("code=".endIndex)
            
            print(code)
            
           // loadAccessToken(code)
            XSUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, callBack: { (isSuccess) -> () in
                if isSuccess{
                    
                    print("请求成功,跳转界面 ")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        
                        NSNotificationCenter.defaultCenter().postNotificationName(XSChangeRootVCNotification, object: self)
                        
                    })
                }else{
                    
                
                    SVProgressHUD.showErrorWithStatus("请求失败")
                    
                }
            })
            
            
            //return false的原因是不用给用户展示回调页
            return false
        }
        
        return true
    }
    
//    //请求AccessToken
//    func loadAccessToken(code:String){
//        
//        let urlStr = "https://api.weibo.com/oauth2/access_token"
//        
//        let parameters = [
//            "client_id" : OA_APPKEY,
//            "client_secret":OA_APP_SECRET,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": OA_redirect_uri
//        ]
//        
//        XSNetworkTools.sharedXSNeworkTool.request(.POST, urlString: urlStr, parameters: parameters, callBack: { (responseObjc, error) -> () in
//            
//            if error != nil{
//                print("\(error)")
//            }
//            print(responseObjc)
//            
//            let account = XSUserAccount(dict: responseObjc!)
//            
//            print(account)
//            
//            self.loadUserInformation(account)
//        })
//
//        
//    }
//    
//    //发送请求获取用户信息
//    private func loadUserInformation(userAccount:XSUserAccount){
//        
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        guard let accessToken = userAccount.access_token,uid = userAccount.uid else{
//            print("请求参数不足")
//            return
//        }
//        
//        let parameters = [
//            
//            "access_token": accessToken,
//            "uid": uid
//        ]
//        
//        XSNetworkTools.sharedXSNeworkTool.request(.GET, urlString: urlString, parameters: parameters) { (responseObjc, error) -> () in
//            
//            if error != nil{
//                print("个人信息请求错误")
//                SVProgressHUD.showErrorWithStatus("个人信息请求错误")
//                return
//            }
//            
//            print("个人信息请求成功\(responseObjc)")
//            
//            userAccount.screen_name = responseObjc!["screen_name"] as? String
//            userAccount.avatar_large = responseObjc!["avatar_large"] as? String
//            
//            
//            //归档
//            
//            let file = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")
//            print("归档文件路径:\(file)")
//            NSKeyedArchiver.archiveRootObject(userAccount, toFile: file)
//            
//            
//            
//        }
//    }
}
